<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Categories extends AdminController {
	
	function Categories() {
		parent::AdminController ();
		
		$this->load->library('Form_validation');
		
		$this->load->model ( "Category_Model", "Categories");
		
		$this->load->helper('language');
		$this->lang->load('admin');
	}
	
	function index($pag = null) {
		$this->load->model("Node_model", "Nodes");
		
		$categories_process = $this->Categories->get(array(
			"status"		=> "all",
			"num_nodes" => TRUE
		));
		
		//TODO Cambiar la forma de contar los nodos...
		
		$this->_addData("categorias", $categories_process);
		
		$this->_render();
	}
	
	
	function add() {
		$referrer = $this->session->userdata("referrer");
		$this->_addData("referrer", $referrer);
		
		$this->_addData("url_form", "admin/categories/add");
		
		$this->form_validation->set_rules('name', 'Categoria', 'required|max_length[60]');
		$this->form_validation->set_rules('url', 'Url', 'required|max_length[200]');
		$this->form_validation->set_rules('visible', 'Visible', 'required');
		$this->form_validation->set_error_delimiters('', '<br />');

		if ($this->form_validation->run() == TRUE)
		{
			$fields = array(
				'parent_id'	=> $this->input->post('parent_id'),
				'name'		=> $this->input->post('name'),
				'url_name'	=> $this->input->post('url'),
				'visible'	=> $this->input->post('visible'),
			);
			
			$category_id = $this->Categories->create($fields);
			
			$this->_process_extra_info($category_id);
			
			$this->_addFlashSuccess("Categoria creada correctamente");
			redirect('admin/categories', 'refresh');
		} else{
			$this->_addData("categorias", $this->Categories->get(array("status" => "all")));	
			$this->_pre_process_extra_info();
		}
		
		$this->_render();
	}
	
	function edit($id = NULL) {
		$this->_setPageView("categories/add");
		
		$referrer = $this->session->userdata("referrer");
		$this->_addData("referrer", $referrer);
		
		$this->_addData("url_form", "admin/categories/edit/$id");
		
		$this->form_validation->set_rules('name', 'Categoria', 'required|max_length[60]');
		$this->form_validation->set_rules('url', 'Url', 'required|max_length[200]');
		$this->form_validation->set_rules('visible', 'Visible', 'required');
		$this->form_validation->set_error_delimiters('', '<br />');

		if ($this->form_validation->run() == TRUE){
			$fields = array(
				'id'		=> $id,
				'parent_id'	=> $this->input->post('parent_id'),
				'name'		=> $this->input->post('name'),
				'url_name'	=> $this->input->post('url'),
				'visible'	=> $this->input->post('visible'),
			);
			
			$this->Categories->update($fields);
			
			$this->_process_extra_info($id);
			
			$this->_addFlashSuccess("Categoria modificada correctamente");
			redirect('admin/categories', 'refresh');
			
		} else{				
		
			if($id != NULL){
				$category = $this->Categories->get(array("id" => $id, "status" => "all"));
				if($category !== FALSE){
					$this->_addData("category_id", $id);
					$this->_addData("category_parent_id", $category->parent_id);
					$this->_addData("category_name", $category->name);
					$this->_addData("category_url_name", $category->url_name);	
					$this->_addData("category_visible", $category->visible);	
				}
				
				$categories =  $this->Categories->get(array("status" => "all"));
				$this->_clearCategory($categories, $id);
				
				$this->_addData("id", $id);
				$this->_addData("categorias", $categories);
				$this->_pre_process_extra_info($id);
			}
		}
		
		$this->_render();
	}
	
	function _pre_process_extra_info($id = NULL){
		$extra_fields = $this->settings->item("categories_columns");
		
		$process_extra_fields = array();
		foreach($extra_fields as $field_name=>$field_info){
			$process_extra_fields[$field_name] = $field_info;
			
			if($id != NULL){
				$f = $this->Categories->getMeta($id, $field_name, TRUE);
				if($f != NULL){
					$process_extra_fields[$field_name]['value'] = $f->meta_value;
				}
			}
		}
		
		$this->_addData("extra_fields", $process_extra_fields);
	}
	
	function _process_extra_info($id = NULL){
		if($id != NULL){
			$extra_fields = $this->settings->item("categories_columns");
			
			foreach($extra_fields as $field_name=>$field_info){
				//Temporal. Tendremos que crear una libreria para tratar form_field
				// lib->get($name)
				
				$old_value = $this->Categories->getMeta($id, $field_name, TRUE);
				if($old_value != NULL){
					$old_value = $old_value->meta_value;
				}
				
				Console::log("OLD VALUE: " . $old_value);
				
				$value = NULL;
				if(isset($field_info['default'])){
					$value = $field_info['default'];
				}
				
				if($field_info['type'] ==  "file"){
					$value = $old_value;
					
					Console::log("Tipo FILE. Nombre del campo: $field_name");
					
					$this->load->library('upload');
					
					$default['upload_path'] = "upload";
					$default['allowed_types'] = 'gif|jpg|png';
					
					$config = array_merge($default, $field_info);
					
					if(!file_exists($config['upload_path'])){
						mkdir($config['upload_path'], 0777, true);
					}
					
					Console::log("UPLOAD PATH: " . $config['upload_path']);
					
					$this->upload->initialize($config);
					
					if ($this->upload->do_upload($field_name)){
						$data = $this->upload->data();
						Console::log("UPLOAD CORRECTO. Data: " . print_r($data, TRUE));
						
						$value = $data['full_path'];
						$value = substr($value, strpos($value, $config['upload_path']));
						if($old_value != NULL && file_exists($old_value)){
							unlink($old_value);
						}
					} else{
						Console::log("ERROR EN EL UPLOAD!!!!!!" . $this->upload->display_errors());
					}
				} else{
					$value = $this->input->post($field_name);
				}
				
				
				if($value != NULL){
					
					if($old_value != NULL && $value != $old_value){
						$this->Categories->updateMeta($id, $field_name, $value);
					} else {
						$this->Categories->addMeta($id, $field_name, $value, TRUE);
					}
				}
			}
		}
	}
	
	function _clearCategory(&$categories, $idCategory){
		foreach($categories as $pos=>$category){
			if($category->id == $idCategory){
				unset($categories[$pos]);
			} else if(isset($category->categories) && count($category->categories)>0){
				$this->_clearCategory($category->categories, $idCategory);
			}
		}
	}

	function delete($id) {
		if($id != null){
			$this->Categories->delete($id);
			$this->_addFlashSuccess("Categoria eliminada correctamente");
		}
		
		redirect ( 'admin/categories', 'refresh' );
	}

}
?>
